package com.yiyuzi.admin.privilege.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yiyuzi.admin.privilege.PrivilegeDao;
import com.yiyuzi.admin.privilege.domain.dto.PrivilegeTreeDTO;
import com.yiyuzi.admin.privilege.domain.entity.PrivilegeEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yiyuzi
 * @date 2021/5/8 13:04
 */

@Service
@Transactional
public class PrivilegeServiceImpl extends ServiceImpl<PrivilegeDao, PrivilegeEntity> implements PrivilegeService {
    @Autowired
    PrivilegeDao privilegeDao;

    @Override
    public PrivilegeEntity findByPath(String path) {
        return privilegeDao.selectOneByPath(path);
    }

    @Override
    public boolean removeNotInIds(List<Long> idList) {
        return privilegeDao.deleteNotInIds(idList);
    }

    @Override
    public PrivilegeTreeDTO listToTree() {
        List<PrivilegeEntity> entityList = this.list();
        // 注意数据库id如果不是连续递增的，这里可能会溢出
        Long fa[] = new Long[entityList.size()+105];
        PrivilegeTreeDTO tree = new PrivilegeTreeDTO();
        Long root = 0L;
        PrivilegeEntity rootEntity = new PrivilegeEntity();
        rootEntity.setId(root);
        rootEntity.setFatherId(root);
        tree.setPrivilegeEntity(rootEntity);

        for(PrivilegeEntity entity : entityList){
            List<Long> stack = new ArrayList<>();
            Long fa_id = entity.getFatherId();
            if(fa_id == null){
                fa_id = root;
            }
            fa[entity.getId().intValue()] = fa_id;

            stack.add(entity.getId());
            while (!fa_id.equals(root)){
                stack.add(fa_id);
                fa_id = fa[fa_id.intValue()];
            }
            tree = getTree(tree, entity, stack);
        }

        return tree;
    }

    private PrivilegeTreeDTO getTree(PrivilegeTreeDTO treeDTO, PrivilegeEntity entity, List<Long> stack){
        Long fa_id = stack.remove(stack.size()-1);
        List<PrivilegeTreeDTO> treeDTOList = treeDTO.getTreeList();
        if (stack.isEmpty()){
            PrivilegeTreeDTO newTree = new PrivilegeTreeDTO();
            newTree.setPrivilegeEntity(entity);
            if (treeDTOList == null) {
                treeDTOList = new ArrayList<>();
            }
            treeDTOList.add(newTree);
            treeDTO.setTreeList(treeDTOList);
        }else {
            for(int i = 0; i < treeDTOList.size(); i++){
                PrivilegeTreeDTO faTree = treeDTOList.get(i);
                if(faTree.getPrivilegeEntity().getId().equals(fa_id)){
                    treeDTOList.set(i, getTree(faTree, entity, stack));
                    treeDTO.setTreeList(treeDTOList);
                    break;
                }
            }
        }
        return treeDTO;
    }
}
